import {$post,$get,$del} from '../utils/request.js'
import Vue from 'vue'
export default {
	namespaced:true,
	state:()=>({
		addressList:[
			// {
			// 	name:'张三丰',
			// 	phone:'18677778888',
			// 	city:'重庆市',
			// 	district:'九龙坡',
			// 	region:'渝高大厦',
			// 	isdefault:true
			// },
			// {
			// 	name:'无忌',
			// 	phone:'18677778888',
			// 	city:'重庆市',
			// 	district:'九龙坡',
			// 	region:'渝高大厦',
			// 	isdefault:false
			// }
		],
		checkIdx:-1 //标志订单页显示的地址
	}),
	getters:{
		checkAddress(state){
			// return 11111
			console.log('address的getters',state.checkIdx);
			// 用户没有录入任何地址、或未设置默认
			
			// 用户设置了默认地址
			
			// 用户设置了默认，但是勾选了非默认
			let {addressList,checkIdx} = state
			if(checkIdx!=-1){
				return addressList[checkIdx]
			}
			for(let i=0;i<addressList.length;i++){
				if(addressList[i].isdefault){
					return addressList[i]
				}
			}
		}
	},
	mutations:{
		addressInitMut(state,datalist){
			state.addressList = datalist
		},
		addressAddMut(state,data){
			state.addressList.push(data)
			uni.navigateBack({
				delta:1
			})
		},
		addressDefaultMut(state,idx){
			state.addressList.forEach((item,index)=>{
				if(index==idx){
					// item.isdefault = true
					Vue.set(item,'isdefault',true)
				}else{
					// item.isdefault = false
					Vue.set(item,'isdefault',false)
				}
			})
			console.log(state.addressList);
		},
		addressDelMut(state,idx){
			state.addressList.splice(idx,1)
		},
		addressCheckIdxMut(state,idx){
			state.checkIdx = idx
			uni.navigateBack({
				delta:1
			})
		}
	},
	actions:{
		addressAddAct(context,data){ //新增
			$post('/classes/CakeAddress',data).then(res=>{
				console.log(res);
				data.objectId = res.objectId
				context.commit('addressAddMut',data)
			})
		},
		addressInitAct(context,userid){ //请求对应用户的地址列表
			$get(`/classes/CakeAddress?where={"userid":"${userid}"}`).then(res=>{
				console.log(res);
				context.commit('addressInitMut',res.results)
			})
		},
		addressDefaultAct(context,idx){ //修改线上默认地址
			let batchObj = {"requests":[]}
			context.state.addressList.forEach((item,index)=>{
				let isdefault = index==idx
				batchObj.requests.push({
					method:'PUT',
					path:`/1.1/classes/CakeAddress/${item.objectId}`,
					body:{isdefault}
				})
			})
			$post('/batch',batchObj).then(res=>{
				context.commit('addressDefaultMut',idx)
			})
		},
		addressDelAct(context,idx){
			let {objectId} = context.state.addressList[idx]
			$del(`/classes/CakeAddress/${objectId}`).then(res=>{
				context.commit('addressDelMut',idx)
			})
		}
	}
}